package co.edu.usbcali.raju.games.chess.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import co.edu.usbcali.raju.db.RajuConnection;

public class DBQuery {
	
	private static DBQuery instance;
	
	public static DBQuery getInstance(){
		if(instance==null){
			instance=new DBQuery();
		}
		return instance;
	}
	
	public double getSimpleFunctionEval(int id,String fen) throws SQLException, ClassNotFoundException{
		String stm="SELECT poseval_value " +
				"FROM ch_positions p,ch_pos_seval pe,ch_ev_function f " +
				"WHERE p.pst_id=pe.poseval_pst_id " +
				"AND pe.poseval_fun_id = ? " +
				"AND p.pst_fen = ?";
		Connection conn=RajuConnection.getInstance().getConn();
		PreparedStatement ps=conn.prepareStatement(stm);
		ps.setString(2, fen);
		ps.setInt(1, id);
		ResultSet rs=ps.executeQuery();
		rs.next();
		double d=rs.getDouble(1);
		rs.close();
		ps.close();
		return d;
	}

	public int setSimpleFunctionEval(int id,String fen,double value) throws SQLException, ClassNotFoundException{
		final int i=id;
		final String f=fen;
		final double v=value;

		Thread t=new Thread(){

			public void run(){
				String stm="INSERT INTO ch_positions (pst_fen) "+
				" VALUES( ?) ";
				Connection conn=null;
				try{
					conn=RajuConnection.getInstance().getConn();
					PreparedStatement ps=conn.prepareStatement(stm);
					ps.setString(1, f);
					ps.executeUpdate();
					ps.close();
					conn.commit();
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				stm="INSERT INTO ch_pos_seval (poseval_pst_id,poseval_fun_id,poseval_value) " +
				" SELECT p.pst_id,  ? , ? "+
				" FROM ch_positions p  " +
				"WHERE  p.pst_fen = ?";
				try{
					PreparedStatement ps=conn.prepareStatement(stm);
					ps.setString(3, f);
					ps.setInt(1, i);
					ps.setDouble(2, v);
					int i=ps.executeUpdate();
					ps.close();
					conn.commit();
				}catch(Exception e){
					System.out.println(e.getMessage());
				}}};
				t.start();
				return 1;
	}
	
	public int setBoard(String fen) throws SQLException, ClassNotFoundException{
		final String f=fen;
		 int i;
		Thread t=new Thread(){
			
		public void run(){
		String stm="INSERT INTO ch_positions (pst_fen) "+
				" VALUES( ?) ";
		try{
		Connection conn=RajuConnection.getInstance().getConn();
		PreparedStatement ps=conn.prepareStatement(stm);
		ps.setString(1, f);
		ps.executeUpdate();
		ps.close();
		conn.commit();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		}};
		t.start();
		return 1;
	}
}
